//
//  TopUpBalanceVC.m
//  PatientApp
//
//  Created by chirui on 2017/5/18.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "TopUpBalanceVC.h"


@interface TopUpBalanceVC ()
{
    NSString * _payType;

}
@property (weak, nonatomic) IBOutlet UITextField *moneyText;
@property (weak, nonatomic) IBOutlet UIButton *wxBtn;
@property (weak, nonatomic) IBOutlet UIButton *aliBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@end

@implementation TopUpBalanceVC

-(void)viewWillDisappear:(BOOL)animated{
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
      [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
   
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11.0) {
        // 针对 9.0 以上的iOS系统进行处理
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _payType = @"wxpay";
    TitleView(@"充值");
    self.wxBtn.selected = YES;
    //微信
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payWxResultOpt:)
                                                 name: WX_NOTIFY_KEY
                                               object:nil];

    //支付宝
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(ZFBSuccess:)
                                                 name: @"zfb"
                                               object:nil];
    

    self.sureBtn.layer.cornerRadius = 5.f;
    self.sureBtn.layer.masksToBounds = YES;

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)wxBtnClick:(UIButton *)sender {
    _payType = @"wxpay";
    self.wxBtn.selected = YES;
    self.aliBtn.selected = NO;
}

- (IBAction)aliBtnClick:(UIButton *)sender {
    _payType = @"alipay";
    self.wxBtn.selected = NO;
    self.aliBtn.selected = YES;
}

- (IBAction)sureBtnClick:(UIButton *)sender {
    
    if (_moneyText.text.length==0||_moneyText.text ==nil) {
        
        SHuiMBhudTextTimeStr(@"充值金额不能为空！");
        
        return;
    }
    if ([_moneyText.text intValue]<=0) {
        
        SHuiMBhudTextTimeStr(@"充值金额无效，请重新输入！");
        
        return;
    }

    [self topUpBanceRequest];
    
}

-(void)topUpBanceRequest {


    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"price":_moneyText.text,
                           @"pay_type":_payType,
                           @"type":@"recharge"
                           };
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(topMoney_payFor_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;

        if ([responseObject[@"code"] intValue]==200) {

            if ([_payType isEqualToString:@"wxpay"]) {

                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [responseObject[@"datas"][@"Appparam"] objectForKey:@"appid"];
                req.partnerId           = [responseObject[@"datas"][@"Appparam"] objectForKey:@"partnerid"];
                req.prepayId            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"prepayid"];
                req.nonceStr            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"noncestr"];
                req.timeStamp           = [[responseObject[@"datas"][@"Appparam"] objectForKey:@"timestamp"] intValue];
                req.package             = [responseObject[@"datas"][@"Appparam"] objectForKey:@"packages"];
                req.sign                = [responseObject[@"datas"][@"Appparam"] objectForKey:@"sign"];

                [WXApi sendReq:req];

            }else {

                NSString *appScheme = @"AllFamily";

                [[AlipaySDK defaultService] payOrder:responseObject[@"datas"][@"pay_string"]  fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);

                }];
            }
        } else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];



}

//微信支付完成通知
-(void)payWxResultOpt:(NSNotification *)notification
{
    PayResp *response=(PayResp*)notification.object;

    if (response.errCode == WXSuccess)
    {

        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alerte.tag = 10001;
        [alerte show];

    }
    else
    {
        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付失败了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerte show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 10001) {
        if (buttonIndex == 0) {
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}
-(void)ZFBSuccess:(NSNotification *)notification {
    
    UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alerte.tag = 10001;
    [alerte show];
}

-(void)dealloc{
    
    //第一种方法.这里可以移除该控制器下的所有通知
    
    NSLog(@"移除了所有的通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
